package com.magic.shop.config;

import com.magic.shop.interceptor.SysUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 使用项目拦截器是需要排除magic的拦截器
 * 必须是WebMvcConfigurer 否则ma编辑界面不显示
 * @author JGMa
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer  {
    //@Autowired
   // private SysUserInterceptor sysUserInterceptor;//返回允许跨域

    private List<String> execludePathList = new ArrayList<>();
    private final String[] frameworkUri = new String[]{"/swagger-resources/**", "/webjars/**", "/v2/**","/v3/**", "/swagger-ui.html/**",
            "/doc.html/**","/favicon.ico","/druid/**","/error","/magic/web/**","/openv1/**","/token/**","/renren-fast/**"};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       // registry.addInterceptor(sysUserInterceptor);//返回允许跨域
        execludePathList.addAll(Arrays.asList(frameworkUri));

        // token和签名移到MagicRequestInterceptor中
//        registry.addInterceptor(openApiAccessInterceptor).addPathPatterns("/**").excludePathPatterns(execludePathList);
//        registry.addInterceptor(signatureInterceptor).addPathPatterns("/openv1/**");
    }

    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 请求常用的三种配置，*代表允许所有，当时你也可以自定义属性（比如header只能带什么，只能是post方式等等）
    //    corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
// 		corsConfiguration.addAllowedOrigin("http://localhost:8080");
//		  String []  allowDomain= {"http://127.0.0.1:8080","http://localhost:8080","http://metajob-admin:8080"};
        String []  allowDomain= {"*"};
//	  	corsConfiguration.setAllowedOrigins(Arrays.asList(allowDomain));
        corsConfiguration.setAllowedOriginPatterns(Arrays.asList(allowDomain));
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }
}
